package com.ncdnapp.core.filter;

import com.ncdnapp.core.entity.Response;
import com.ncdnapp.core.entity.enums.ResultEnum;
import com.ncdnapp.core.exception.BussinessException;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.exception.StatusException;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import org.noear.solon.core.handle.Result;
import org.noear.solon.validation.ValidatorException;

/**
 * 统一异常处理
 */
@Component(index = 2)
public class ExcpRspFilter implements Filter {
    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        try {
            chain.doFilter(ctx);
        } catch (ValidatorException e) {
            ctx.render(Response.fail(ResultEnum.REQUEST_PARAM_PARSE_ERR.getCode(), e.getMessage()));
        } catch (StatusException e) {
            if (e.getCode() == 404) {
                ctx.render(Response.fail(ResultEnum.CONTROLLER_NOT_FIND.getCode(), ResultEnum.CONTROLLER_NOT_FIND.getMsg()));
            } else {
                ctx.render(Response.fail(ResultEnum.SERVICE_ERR.getCode(), e.getMessage()));
            }
        } catch (BussinessException e) {
            ctx.render(Result.failure(e.getCode(), e.getMsg()));
        } catch (Throwable e) {
            ctx.render(Response.fail(ResultEnum.SERVICE_ERR.getCode(), ResultEnum.SERVICE_ERR.getMsg()));
        }
    }
}
